package com.bhs.sansong.ui.shipments;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.ArrayMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bhs.sansong.R;
import com.bhs.sansong.adapter.AddressBookAdapter;
import com.bhs.sansong.base.BaseActivity;
import com.bhs.sansong.base.BaseBean;
import com.bhs.sansong.bean.AddressInfo;
import com.bhs.sansong.bean.AddressList;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.utils.MyUtils;
import com.bhs.sansong.utils.ToastUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 地址薄
 */
public class AddressBookActivity extends BaseActivity implements NetCallBack, View.OnClickListener {

    private EditText mEtSearch;
    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRvList;
    private int page = 1;
    private AddressBookAdapter mAdapter;
    private int deletePosition;
    private int type = 0;

    @Override
    public int initLayout() {
        return R.layout.activity_address_book;
    }

    @Override
    public void initView() {
        type = getIntent().getIntExtra("type", 0);
        TextView mTvTitle = findViewById(R.id.tv_title);
        mTvTitle.setText("地址薄");
        mEtSearch = findViewById(R.id.et_search);
        mRefreshLayout = findViewById(R.id.refreshLayout);
        mRvList = findViewById(R.id.rv_list);
        findViewById(R.id.btn_confirm).setOnClickListener(this);
    }

    @Override
    public void initData() {
        mAdapter = new AddressBookAdapter();
        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(mActivity));

        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                loadData("");

            }
        });

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                page++;
                loadData("");
            }
        }, mRvList);

        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //点击搜索要做的操作
                    page = 1;
                    loadData(mEtSearch.getText().toString());
                    return true;
                }
                return false;
            }
        });

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (type == 0) {
                    Intent i = new Intent();
                    i.putExtra("info", mAdapter.getData().get(position));
                    setResult(getIntent().getIntExtra("type", 0), i);
                    finish();
                }
            }
        });

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                AddressInfo info = mAdapter.getData().get(position);
                if (view.getId() == R.id.cb_default) {
                    for (AddressInfo datum : mAdapter.getData()) {
                        datum.setIs_default(0);
                    }
                    info.setIs_default(1);
                    mAdapter.notifyDataSetChanged();
                    networkRequest(netApi.set_default_address(info.getAddress_id()), AddressBookActivity.this, 888);
                } else if (view.getId() == R.id.tv_edit) {
                    Intent intent = new Intent(mActivity, CompleteAddressActivity.class);
                    intent.putExtra("id", info.getAddress_id());
                    intent.putExtra("type", 4);
                    startActivity(intent);
                } else if (view.getId() == R.id.tv_delete) {
                    deletePosition = position;
                    new XPopup.Builder(mActivity)
                            .asConfirm("提示", "确定删除吗",
                                    "取消", "确定",
                                    new OnConfirmListener() {
                                        @Override
                                        public void onConfirm() {
                                            networkRequest(netApi.del_address(info.getAddress_id()), AddressBookActivity.this, 666);
                                        }
                                    }, null, false)
                            .show();
                }
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        page = 1;
        loadData("");
    }

    Map<String, String> map = new ArrayMap<>();

    private void loadData(String search_key) {
        map.put("page", String.valueOf(page));
        map.put("search_key", search_key);
        networkRequest(netApi.get_address_list(map), this);
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 0) {
            AddressList bean = new Gson().fromJson(json, AddressList.class);
            mRefreshLayout.setRefreshing(false);
            if (bean.isStatus()) {
                if (page == 1) {
                    mAdapter.setNewData(bean.getData().getAddressInfoList());
                } else {
                    mAdapter.loadMoreComplete();
                    mAdapter.addData(bean.getData().getAddressInfoList());
                }
                if (mAdapter.getData().size() >= bean.getData().getTotal_count()) {
                    mAdapter.loadMoreEnd();
                }
            }
        } else if (requestCode == 666) {
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            ToastUtil.show(bean.getMsg());
            if (bean.isStatus()) {
                mAdapter.remove(deletePosition);
            }
        } else if (requestCode == 888) {
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            ToastUtil.show(bean.getMsg());
        }
    }

    @Override
    public void onFailure(int requestCode) {
        mRefreshLayout.setRefreshing(false);
        mAdapter.loadMoreComplete();
    }

    @Override
    public void onClick(View view) {
        Intent intent = new Intent(this, CompleteAddressActivity.class);
        intent.putExtra("type", 3);
        startActivity(intent);
    }
}